#!/bin/bash
set -ex

MIRRORS_URL=https://mirrors.ustc.edu.cn
BASE_URL=$MIRRORS_URL/alpine/v3.15/releases/x86_64/alpine-minirootfs-3.15.0-x86_64.tar.gz
TAR_NAME=rootfs.alpine.tar.gz


einfo() {
	printf '\n\033[1;36m> %s\033[0m\n' "$@" >&2  # bold cyan
}

make_rootfs(){
    einfo 'Make rootfs...'
    if [ ! -d rootfs ];then
        mkdir rootfs
    fi
    rm -rf rootfs/*
    if [ ! -s *.tar.gz ];then
        curl -fLO $BASE_URL 
    fi
    tar -zxpf *.tar.gz -C rootfs
}

prepare_chroot(){
    einfo 'Prepare chroot...'
    cp -rf content/* rootfs/
    cp -f /etc/resolv.conf rootfs/etc/resolv.conf
}

install_chroot(){
    einfo 'Installing chroot...'
    cp chroot rootfs/chroot
    chmod +x rootfs/chroot
    chroot rootfs /bin/ash -c "sh chroot"
    rm rootfs/chroot
}

archive_rootfs(){
    einfo 'Creating rootfs archive...'
    if [ ! -d tars ];then
        mkdir tars
    fi
    cd rootfs;
    tar -zcpf ../tars/$TAR_NAME `ls`
    cd ..;
    chown `id -un` tars/$TAR_NAME
}

clean_up(){
    einfo 'Clear Up...'
    rm -rf rootfs
    rm *.tar.gz
}

make_rootfs
prepare_chroot
install_chroot
archive_rootfs
clean_up